package com.henry.base.concurrency;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class TrafficLight {
    private CyclicBarrier barrier;
    private CountDownLatch latch;

    public TrafficLight(CyclicBarrier barrier, CountDownLatch latch) {
        this.barrier = barrier;
        this.latch = latch;
    }

    public void peopleWaitRedLight(){
        try {
            this.barrier.await();
            System.out.println("凑够数了，大家一起闯红灯...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }finally {
            if (latch != null) {
                latch.countDown();
            }
        }
    }

    public void driverWaitRedLight(){
        try {
            latch.await();
            Thread.sleep(1000);//等一秒，让行人完全走过去
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
